package ppos2.kmlgenerator;

import java.io.*;

public class KMLgenerator {
	
	// Header and footer for the KML files
	private String header = new String("<?xml version=\"1.0\" encoding=\"UTF-8\"?> <kml xmlns=\"http://www.opengis.net/kml/2.2\">");
	private String footer = new String ("</kml>");

	private double initialLat = 56.144;
	private double initialLong = 10.199;
	
	private double defaultAlt = 0.0;
	private double defaultHeading = 103.8120432044965; 
	private double defaultTilt = 62.04855796276328;
	private double defaultRange =2889.145007690472;
	
	private String pathLine = new String("");
	
	// Writer and File class for KML file generation
	private Writer output = null;
	private File file = null;
	
	// Generates the initial location and the description
	private String generateInitialData(String name, int visibility)
	{
		return ("<name>" + name + "</name><visibility>" + String.valueOf(visibility) + " </visibility> <description>Test set</description>");
	}
	
	// Generate the "LookAt" initial point
	private String generateLookAt(double latitude, double longitude, double altitude, double heading, double tilt, double range)
	{
		return ("<LookAt> <longitude>" +
				String.valueOf(longitude) +
				"</longitude> <latitude>" + 
				String.valueOf(latitude) +
				"</latitude> <altitude> " +
				String.valueOf(altitude) +
				"</altitude> <heading>" +
				String.valueOf(heading) +
				"</heading> <tilt>" +
				String.valueOf(tilt)+
				"</tilt> <range>" + 
				String.valueOf(range) +
				"</range> </LookAt>");
	}	
	
	public KMLgenerator() {
		super();
	}
	
	public String generateLineString(int tessellate, String csvCollection)
	{		
		this.pathLine = "<LineString><tessellate>" + String.valueOf(tessellate) + "</tessellate>";
		this.pathLine = this.pathLine + "<coordinates>";
		
		// Coordinates in CSV format should be placed between these two tags
		this.pathLine = this.pathLine + csvCollection;
		
		this.pathLine = this.pathLine + "</coordinates>";
		this.pathLine = this.pathLine + "</LineString>";
		
		return this.pathLine;
	}

	// Generation of the KML file
	public void generateFile(String csvCollection) throws IOException {
		
		String pathLine = new String();
		
		file = new File("path.kml");
		output = new BufferedWriter(new FileWriter(file));
		
		output.write(header);
		output.write("<Placemark>");

		output.write(generateLookAt(this.initialLat,this.initialLong,this.defaultAlt,this.defaultHeading, this.defaultTilt,this.defaultRange));
		
		output.write(generateInitialData(new String("Aarhus"), 1));

		output.write(generateLineString(1,csvCollection));	
		
		System.out.print("\nGenerated LineString: " + pathLine);
		
		output.write("</Placemark>");
		output.write(footer);
	
		output.close();
	}
	
}
